//
//  AppDelegate.m
//  StarLight
//
//  Created by Duke.wu on 16/5/9.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//  commit code 2017.5.25

#import "AppDelegate.h"
#import "NSDate+Utils.h"
#import "DateTools.h"
#import "SLRootViewControllerConfig.h"
#import <QMapKit/QMapKit.h>
#import <QMapSearchKit/QMapSearchKit.h>
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import <UMMobClick/MobClick.h>
#import "SLUserManager.h"
#import "GeTuiSdk.h"     // GetuiSdk头文件，需要使用的地方需要添加此代码
#import "SLProductDetailViewController.h"
#import "SLBoatDetailViewController.h"
#import "BKJH5ViewController.h"
#import "SLMessageCenterViewController.h"
#import "UMMobClick/MobClick.h"
#import "LLTabBar.h"
#import "SLHomeViewController.h"
#import "SLDeployViewController.h"
#import "SLInformationViewController.h"
#import "SLNewMineViewController.h"
#import "SLAddBoatViewController.h"
#import "SLUpDataWatercraftView.h"



/// 个推开发者网站中申请App时，注册的AppId、AppKey、AppSecret
#define kGtAppId           @"axh51mF88wAo9npeOtEo96"
#define kGtAppKey          @"Y8rZ0imevt9w1QWPVhxDA7"
#define kGtAppSecret       @"YnG7QKF3JQ7lrLMFOyrSZ3"




@interface AppDelegate ()<GeTuiSdkDelegate,LLTabBarDelegate>

@property (nonatomic, strong) SLRootViewControllerConfig *rootConfig;

@property (nonatomic ,copy) NSString *usertype;

@property (nonatomic, strong) SLUpDataWatercraftView *watercraftView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
  [self ANPSSeting];
  [self isTheFirstUse];
  [self setupUMeng];
  [self someSettingsOfUI];
  [self QMapConfig];
  [self addNotifications];
  [self setRootVC];
    [self setupView];
  return YES;
}

- (void)ANPSSeting{
  [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
  // 注册APNS
  [self registerUserNotification];
  
}
- (void)someSettingsOfUI{
  [[UITextField appearance] setTintColor:SLYellowColor];
  [[UINavigationBar appearance] setBarTintColor:SLBlackColor];
  [[UINavigationBar appearance] setTintColor:SLYellowColor];
  [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName: SLYellowColor };
  [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
  [SVProgressHUD setMinimumDismissTimeInterval:2];
}

#pragma mark - methods

- (void)QMapConfig{
  [[QMSSearchServices sharedServices] setApiKey:@"OBBBZ-GMU32-DWSUD-CSTIH-M7AAE-K7BUD"];
  [QMapServices sharedServices].apiKey = @"OBBBZ-GMU32-DWSUD-CSTIH-M7AAE-K7BUD";
  
}

- (void)setRootVC{
  
  if ([DEFAULTS boolForKey:@"isLogined"]) {
    
    // 如果 token 过期重新登录;
    NSString *userDate = [DEFAULTS objectForKey:loginInfo][@"expiry"];
    NSString *today = [NSDate stringYearMonthDayWithDate:nil];
    if ([userDate isEqualToString:today]) {
      [SVProgressHUD showImage:nil status:@"身份过期请重新登录"];
      self.window.rootViewController = self.rootConfig.loginNavi;
    }else{
      self.window.rootViewController = [self RootTabbar];
    }

  }else{
    self.window.rootViewController = self.rootConfig.loginNavi;
  }
}



- (void)setupView
{
    SLUpDataWatercraftView *watercraftView = [[SLUpDataWatercraftView alloc]initWithModelView];
    
    watercraftView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    watercraftView.hidden = YES;
    
    self.watercraftView = watercraftView;
    
    [self.window addSubview:watercraftView];
}

- (void)addNotifications{
  
  @weakify(self)
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kNotificationToChangeRootVC object:nil] subscribeNext:^(id x) {
    @strongify(self)
    self.window.rootViewController = [self RootTabbar];
    self.rootConfig.loginNavi = nil;
  }];
  
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kNotificationRootVCToLoginVC object:nil] subscribeNext:^(id x) {
    @strongify(self)
    self.window.rootViewController = self.rootConfig.loginNavi;
    UITabBarController *tabbar = [self RootTabbar];
      tabbar = nil;
  }];
    
  //动态改变tabbar中间按钮的图标
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kCHANGETYPE object:nil] subscribeNext:^(NSNotification *notification) {
    @strongify(self)
    if ([notification.object isEqual:@(0)]) {
        self.usertype = @"Untitled";//船东版
        self.window.rootViewController = [self RootTabbar];
    }
    else{
        self.usertype = @"ic_tab_shuaxin";//货主版
        self.window.rootViewController = [self RootTabbar];
    }
  }];
}

- (void)isTheFirstUse{
  // 储存一个值 用来在下方判断是否是第一次使用app
  if (![DEFAULTS boolForKey:@"everLaunched"]) {
    [DEFAULTS setBool:YES forKey:@"everLaunched"];
    [DEFAULTS setBool:YES forKey:@"firstLaunch"];
    
    // 如果是第一次使用，那么就设定为未登陆
    [DEFAULTS setBool:NO forKey:@"isLogined"];
    [DEFAULTS synchronize];
  }
  else{
    [DEFAULTS setBool:NO forKey:@"firstLaunch"];
    [DEFAULTS synchronize];
  }
}


- (void)starReachability{
  Reachability *reac = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kReachabilityChangedNotification object:nil] subscribeNext:^(id x) {
    
    
  }];
  [reac startNotifier];
}

#pragma mark - UMeng
- (void)setupUMeng{
  [UMSocialData setAppKey:kUMengAppKey];
  [UMSocialWechatHandler setWXAppId:kWeChatAppKey appSecret:KWeChatAppSecret url:@"www.xinmatou.net"];
  [UMSocialQQHandler setQQWithAppId:KQQAppId appKey:kQQAppKey url:@"www.xinmatou.net"];
  UMConfigInstance.appKey = kUMengAppKey;
  UMConfigInstance.channelId = @"App Store";
  [MobClick setLogEnabled:YES];
  [MobClick startWithConfigure:UMConfigInstance];
}



#pragma mark - 个推设置

#pragma mark - 用户通知(推送) _自定义方法

/** 注册用户通知 */
- (void)registerUserNotification {
  
  /*
   注册通知(推送)
   申请App需要接受来自服务商提供推送消息
   */
  // 判读系统版本是否是“iOS 8.0”以上
  if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
      [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
    
    // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
    UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    
    // 定义用户通知设置
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    
    // 注册用户通知 - 根据用户通知设置
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  }else { // iOS8.0 以前远程推送设置方式
    // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
    UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    
    // 注册远程通知 -根据远程通知类型
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
  }

}

#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用

/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  // 注册远程通知（推送）
  [application registerForRemoteNotifications];
}

#pragma mark - 远程通知(推送)回调

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
  token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
  
  
  // [3]:向个推服务器注册deviceToken
  [GeTuiSdk registerDeviceToken:token];
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  
}

#pragma mark - APP运行中接收到通知(推送)处理

/** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台) */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  application.applicationIconBadgeNumber = 0; // 标签
  DLog(@"userInfo == %@",userInfo);
}

/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
  
  // 处理APN
  DLog(@"%@",userInfo);
  completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
  // [4-EXT-1]: 个推SDK已注册，返回clientId
  NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
  // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
  NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}


/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
  
  if (payloadData && offLine) {
     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingMutableLeaves error:nil];
    DLog(@"%@",dic);
    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
      if ([dic[@"type"] integerValue] == 1) {
        SLProductDetailViewController *goodsDetailVC = [SLProductDetailViewController new];
        [goodsDetailVC changeGid:dic[@"gid"]];
        [(UINavigationController *)self.window.rootViewController pushViewController:goodsDetailVC animated:YES];
      }else if ([dic[@"type"] integerValue] == 2){
        SLBoatDetailViewController *boatDetailVC = [SLBoatDetailViewController new];
        [boatDetailVC changeBid:dic[@"bid"]];
        [(UINavigationController *)self.window.rootViewController pushViewController:boatDetailVC animated:YES];
      }else if ([dic[@"type"] integerValue] == 3){
        BKJH5ViewController *h5VC = [BKJH5ViewController new];
        h5VC.h5Url = dic[@"url"];
        [(UINavigationController *)self.window.rootViewController pushViewController:h5VC animated:YES];
      }else if([dic[@"type"] integerValue] == 0){
        SLMessageCenterViewController *msgCenterVC = [SLMessageCenterViewController new];
        [(UINavigationController *)self.window.rootViewController pushViewController:msgCenterVC animated:YES];
      }

//    });
    
  }
 

}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
  // [4-EXT]:发送上行消息结果反馈
  NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
  NSLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
  // [EXT]:通知SDK运行状态
  NSLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
  if (error) {
    NSLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
    return;
  }
  NSLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}



#pragma mark Ping ++

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
  BOOL result = [UMSocialSnsService handleOpenURL:url];
  if (result == FALSE) {
     result = [Pingpp handleOpenURL:url withCompletion:nil];
  }
  return result;
  
}


- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary *)options {
  BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
  return canHandleURL;
}



- (void)applicationWillResignActive:(UIApplication *)application {
 
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
  
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
  
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  application.applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application {
  
}


- (UITabBarController *)RootTabbar{

    SLHomeViewController *homeViewController = [[SLHomeViewController alloc] init];
    UINavigationController *homeNav = [[UINavigationController alloc] initWithRootViewController:homeViewController];
    [homeNav setNavigationBarHidden:YES animated:YES];
    
    SLDeployViewController *sameCityViewController = [[SLDeployViewController alloc] init];
    UINavigationController *sameNav = [[UINavigationController alloc] initWithRootViewController:sameCityViewController];
    [sameNav setNavigationBarHidden:YES animated:YES];
    
    SLInformationViewController *messageViewController = [[SLInformationViewController alloc] init];
    UINavigationController *messageNa = [[UINavigationController alloc] initWithRootViewController:messageViewController];
    [messageNa setNavigationBarHidden:YES animated:YES];
    
    SLNewMineViewController *mineViewController = [[SLNewMineViewController alloc] init];
    UINavigationController *mineNav = [[UINavigationController alloc] initWithRootViewController:mineViewController];
    [mineNav setNavigationBarHidden:YES animated:YES];
    
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    tabBarController.viewControllers = @[homeNav, sameNav, messageNa, mineNav];
    
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    //船东版
    if ([[DEFAULTS objectForKey:@"userType"]  isEqual: @(0)]) {
       self.usertype = @"Untitled";//船东版
    }
    //货主版
    if ([[DEFAULTS objectForKey:@"userType"]  isEqual: @(1)]){
        self.usertype = @"ic_tab_shuaxin";//货主版
    }
    
    LLTabBar *tabBar = [[LLTabBar alloc] initWithFrame:tabBarController.tabBar.bounds];
    tabBar.tabBarItemAttributes = @[@{kLLTabBarItemAttributeTitle : @"首页", kLLTabBarItemAttributeNormalImageName : @"ic_tab_shouye_nor", kLLTabBarItemAttributeSelectedImageName : @"ic_tab_shouye_sel", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"配载", kLLTabBarItemAttributeNormalImageName : @"recommend-1", kLLTabBarItemAttributeSelectedImageName : @"recommend", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"", kLLTabBarItemAttributeNormalImageName : self.usertype, kLLTabBarItemAttributeSelectedImageName : self.usertype, kLLTabBarItemAttributeType : @(LLTabBarItemRise)},
                                    @{kLLTabBarItemAttributeTitle : @"资讯", kLLTabBarItemAttributeNormalImageName : @"information-1", kLLTabBarItemAttributeSelectedImageName : @"information", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)},
                                    @{kLLTabBarItemAttributeTitle : @"我的", kLLTabBarItemAttributeNormalImageName : @"my-1", kLLTabBarItemAttributeSelectedImageName : @"my", kLLTabBarItemAttributeType : @(LLTabBarItemNormal)}];
    tabBar.delegate = self;
    [tabBarController.tabBar addSubview:tabBar];
    return tabBarController;
}


#pragma mark - LLTabBarDelegate

- (void)tabBarDidSelectedRiseButtonWithController:(UIViewController *)ctr {
    
    //船东版
//    if ([[DEFAULTS objectForKey:@"userType"]  isEqual: @(0)]) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:kCDTYPE object:nil];
//    }
//    //货主版
//    if ([[DEFAULTS objectForKey:@"userType"]  isEqual: @(1)]){
//        [[NSNotificationCenter defaultCenter] postNotificationName:kHZTYPE object:nil];
//        SLAddBoatViewController *goodsDetailVC = [SLAddBoatViewController new];
//        [(UINavigationController *)self.window.rootViewController pushViewController:goodsDetailVC animated:YES];
//    }
    
    //船东版
    if ([self.usertype isEqualToString:@"Untitled"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kCDTYPE object:nil];
        
//        self.watercraftView.hidden = NO;
//        self.watercraftView.parentController = ctr;
    }
    
    //货主版
    if ([self.usertype isEqualToString:@"ic_tab_shuaxin"]){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kHZTYPE object:nil];
//        SLAddBoatViewController *goodsDetailVC = [SLAddBoatViewController new];
//        [(UINavigationController *)self.window.rootViewController pushViewController:goodsDetailVC animated:YES];
    }
}


#pragma mark - getter

- (SLRootViewControllerConfig *)rootConfig{
  if (!_rootConfig) {
    _rootConfig = [[SLRootViewControllerConfig alloc] init];
  }
  return _rootConfig;
}


@end
